<template>
  <Dialog v-model="dialogVisible" title="异常处理" width="800px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="异常信息">
        <el-card class="exception-info">
          <div class="info-row">
            <span class="label">异常类型：</span>
            <el-tag :type="getExceptionTypeColor(exceptionInfo.exceptionType)">
              {{ exceptionInfo.exceptionType }}
            </el-tag>
          </div>
          <div class="info-row">
            <span class="label">发生时间：</span>
            <span>{{ exceptionInfo.occurTime }}</span>
          </div>
          <div class="info-row">
            <span class="label">影响范围：</span>
            <span>{{ exceptionInfo.affectedScope }}</span>
          </div>
          <div class="info-row">
            <span class="label">严重程度：</span>
            <el-tag :type="getSeverityColor(exceptionInfo.severity)">
              {{ exceptionInfo.severity }}
            </el-tag>
          </div>
          <div class="info-row">
            <span class="label">异常描述：</span>
            <span>{{ exceptionInfo.description }}</span>
          </div>
        </el-card>
      </el-form-item>
      
      <el-form-item label="处理方式" prop="handleType">
        <el-radio-group v-model="formData.handleType" @change="handleTypeChange">
          <el-radio label="立即处理">立即处理</el-radio>
          <el-radio label="延后处理">延后处理</el-radio>
          <el-radio label="转交处理">转交处理</el-radio>
          <el-radio label="忽略异常">忽略异常</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item label="处理措施" prop="handleMeasures">
        <el-select
          v-model="formData.handleMeasures"
          placeholder="请选择处理措施"
          style="width: 100%"
          multiple
        >
          <el-option label="重启服务" value="重启服务" />
          <el-option label="数据修复" value="数据修复" />
          <el-option label="流程回滚" value="流程回滚" />
          <el-option label="手动干预" value="手动干预" />
          <el-option label="系统维护" value="系统维护" />
          <el-option label="通知相关人员" value="通知相关人员" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="处理说明" prop="handleDescription">
        <el-input
          v-model="formData.handleDescription"
          type="textarea"
          :rows="4"
          placeholder="请详细描述处理过程和结果"
        />
      </el-form-item>
      
      <el-form-item label="预计处理时间" v-if="formData.handleType === '延后处理'">
        <el-date-picker
          v-model="formData.scheduledTime"
          type="datetime"
          placeholder="请选择预计处理时间"
          style="width: 100%"
        />
      </el-form-item>
      
      <el-form-item label="转交给" v-if="formData.handleType === '转交处理'" prop="assigneeId">
        <el-select
          v-model="formData.assigneeId"
          placeholder="请选择处理人员"
          style="width: 100%"
          filterable
        >
          <el-option
            v-for="user in userList"
            :key="user.id"
            :label="user.nickname"
            :value="user.id"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="转交说明" v-if="formData.handleType === '转交处理'">
        <el-input
          v-model="formData.assignComments"
          type="textarea"
          :rows="3"
          placeholder="请输入转交说明"
        />
      </el-form-item>
      
      <el-form-item label="忽略原因" v-if="formData.handleType === '忽略异常'" prop="ignoreReason">
        <el-input
          v-model="formData.ignoreReason"
          type="textarea"
          :rows="3"
          placeholder="请输入忽略此异常的原因"
        />
      </el-form-item>
      
      <el-form-item label="后续跟进">
        <el-checkbox-group v-model="formData.followUpActions">
          <el-checkbox label="监控恢复">持续监控恢复情况</el-checkbox>
          <el-checkbox label="定期检查">定期检查相关功能</el-checkbox>
          <el-checkbox label="预防措施">制定预防措施</el-checkbox>
          <el-checkbox label="文档记录">更新异常处理文档</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      
      <el-form-item label="处理附件">
        <el-upload
          v-model:file-list="formData.attachments"
          action="#"
          :auto-upload="false"
          multiple
        >
          <el-button type="primary">选择文件</el-button>
          <template #tip>
            <div class="el-upload__tip">
              支持上传处理过程截图、日志文件等，单个文件不超过10MB
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button 
        @click="submitHandle" 
        type="primary" 
        :disabled="!canSubmit"
        :loading="formLoading"
      >
        提交处理结果
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

defineOptions({ name: 'ExceptionHandle' })

const emit = defineEmits(['success'])

const dialogVisible = ref(false)
const formLoading = ref(false)
const formRef = ref()
const userList = ref([])

const exceptionInfo = reactive({
  id: undefined,
  exceptionType: '',
  occurTime: '',
  affectedScope: '',
  severity: '',
  description: ''
})

const formData = reactive({
  handleType: '立即处理',
  handleMeasures: [],
  handleDescription: '',
  scheduledTime: null,
  assigneeId: undefined,
  assignComments: '',
  ignoreReason: '',
  followUpActions: [],
  attachments: []
})

const formRules = reactive({
  handleType: [{ required: true, message: '请选择处理方式', trigger: 'change' }],
  handleMeasures: [{ required: true, message: '请选择处理措施', trigger: 'change' }],
  handleDescription: [{ required: true, message: '请输入处理说明', trigger: 'blur' }],
  assigneeId: [{ required: true, message: '请选择处理人员', trigger: 'change' }],
  ignoreReason: [{ required: true, message: '请输入忽略原因', trigger: 'blur' }]
})

const canSubmit = computed(() => {
  if (!formData.handleType || formData.handleMeasures.length === 0 || !formData.handleDescription.trim()) {
    return false
  }
  
  if (formData.handleType === '转交处理' && !formData.assigneeId) {
    return false
  }
  
  if (formData.handleType === '忽略异常' && !formData.ignoreReason.trim()) {
    return false
  }
  
  return true
})

/** 打开弹窗 */
const open = async (exception: any) => {
  dialogVisible.value = true
  Object.assign(exceptionInfo, exception)
  await loadUserList()
  resetForm()
}

/** 加载用户列表 */
const loadUserList = async () => {
  try {
    // TODO: 调用获取用户列表的API
    userList.value = []
  } catch (error) {
    console.error('加载用户列表失败:', error)
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.handleType = '立即处理'
  formData.handleMeasures = []
  formData.handleDescription = ''
  formData.scheduledTime = null
  formData.assigneeId = undefined
  formData.assignComments = ''
  formData.ignoreReason = ''
  formData.followUpActions = []
  formData.attachments = []
  formRef.value?.resetFields()
}

/** 处理方式变更 */
const handleTypeChange = () => {
  // 清空相关字段
  formData.scheduledTime = null
  formData.assigneeId = undefined
  formData.assignComments = ''
  formData.ignoreReason = ''
}

/** 获取异常类型颜色 */
const getExceptionTypeColor = (type: string) => {
  const colorMap = {
    '系统异常': 'danger',
    '数据异常': 'warning',
    '流程异常': 'info',
    '网络异常': 'primary'
  }
  return colorMap[type] || 'info'
}

/** 获取严重程度颜色 */
const getSeverityColor = (severity: string) => {
  const colorMap = {
    '高': 'danger',
    '中': 'warning',
    '低': 'success'
  }
  return colorMap[severity] || 'info'
}

/** 提交处理结果 */
const submitHandle = async () => {
  if (!formRef.value) return
  
  const valid = await formRef.value.validate()
  if (!valid) return
  
  try {
    if (formData.handleType === '忽略异常') {
      await ElMessageBox.confirm(
        '确认忽略此异常吗？忽略后异常将不再提醒。',
        '确认忽略',
        { type: 'warning' }
      )
    }
    
    formLoading.value = true
    
    const handleData = {
      exceptionId: exceptionInfo.id,
      handleType: formData.handleType,
      handleMeasures: formData.handleMeasures,
      handleDescription: formData.handleDescription,
      scheduledTime: formData.scheduledTime,
      assigneeId: formData.assigneeId,
      assignComments: formData.assignComments,
      ignoreReason: formData.ignoreReason,
      followUpActions: formData.followUpActions,
      attachments: formData.attachments
    }
    
    // TODO: 调用处理异常的API
    // await handleException(handleData)
    
    ElMessage.success('异常处理提交成功')
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('异常处理失败:', error)
      ElMessage.error('异常处理失败')
    }
  } finally {
    formLoading.value = false
  }
}

defineExpose({ open })
</script>

<style scoped>
.exception-info {
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.info-row:last-child {
  margin-bottom: 0;
}

.label {
  font-weight: bold;
  min-width: 80px;
  color: #606266;
  margin-right: 10px;
}

.el-checkbox-group {
  display: flex;
  flex-wrap: wrap;
}

.el-checkbox {
  margin-right: 20px;
  margin-bottom: 10px;
}
</style>
